// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
// 引用element ui自定义主题
import '../theme/index.css'
import store from './store'
import router from './router'
import common from './utils/common'
import filters from './utils/filters'
import flexible from './utils/flexible'
import axios from './utils/request'
import App from './App'
import './style/reset.less'
import './style/style.less'
import './style/theme.less'
import 'babel-polyfill'
import Echarts from 'echarts'

Vue.config.productionTip = false
Vue.use(ElementUI)

Vue.prototype.$http = axios
Vue.prototype.$method = common
Vue.prototype.$filter = filters
Vue.prototype.$echarts = Echarts

flexible.remDesign(1920, 1920)

// 全局引入过滤器
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key])
})

router.beforeEach((to, from, next) => {
    // next()
    if (to.path === '/login') {
        next()
    } else {
        setTimeout(() => {
            if (!store.getters.user) {
                store.dispatch('loginBySession').then(res => {
                    if (!res) {
                        next('/login')
                    } else {
                        // 动态添加可访问路由表
                        store.dispatch('generateAllRouters', store).then(routers => {
                            router.options.routes.push(...routers)
                            router.addRoutes(routers)
                            // 标记路由已动态更改
                            store.dispatch('updateRouters')
                            routeRedirect(next, store, to, true)
                        })
                        routeRedirect(next, store.getters.user, to, true)
                    }
                })
            } else {
                routeRedirect(next, store, to)
            }
        }, 0)
    }

    function routeRedirect(next, store, to, replace) {
        let obj = router.options.routes.find((item) => {
            return item.path === ('/' + to.path.split('/')[1])
        })
        if (obj && obj.path && to.path !== '/') {
            if (replace) {
                next({...to, replace: true})
            } else {
                next(...to)
            }
        } else {
            next({...to, replace})
        }
    }
})

// // 路由跳转后更新主题显示区域，刷新滚动条
router.afterEach((to, from) => {
    window.$history++
})

/* eslint-disable no-new */
window.$vm = new Vue({
    el: '#app',
    router,
    store,
    components: {App},
    template: '<App/>'
})

if (!window.localStorage.getItem('ajaxApi')) window.localStorage.setItem('ajaxApi', '/_api')
window.$history = 0
